package com.fixme4trade.view;

import java.io.IOException;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.inject.Inject;

import org.primefaces.event.FileUploadEvent;

import br.gov.frameworkdemoiselle.annotation.Name;
import br.gov.frameworkdemoiselle.annotation.PreviousView;
import br.gov.frameworkdemoiselle.stereotype.ViewController;
import br.gov.frameworkdemoiselle.transaction.Transactional;
import com.fixme4trade.business.ProductBC;
import com.fixme4trade.business.UserBC;
import com.fixme4trade.domain.Image;
import com.fixme4trade.domain.Product;
import com.fixme4trade.domain.Seller;
import com.fixme4trade.template.DelegateEditPageBean;
import com.fixme4trade.util.FileUploader;

@ViewController
@PreviousView("/auth/index.xhtml")
public class ProductEditMB extends DelegateEditPageBean<Product, Long, ProductBC> {

	private static final long serialVersionUID = 1L;
	
	@Inject
	private UserBC userBC;	

	@Override
	@Transactional
	public String delete() {
		return super.delete();
	}

	@Override
	@Transactional
	public String insert() {
		Seller seller = userBC.getAuthenticatedSeller();		
		super.getBean().setOwner(seller);
		
		return super.insert();
	}

	@Override
	@Transactional
	public String update() {
		return super.update();
	}
		
	private DataModel<Image> images;
	/*
	public void addImage() {
		getBean().getImageList().add(new Image());		
	}
	*/

	public void deleteImage() {
		getBean().getImageList().remove(getImages().getRowData());
	}
	

	public DataModel<Image> getImages() {
		if (images == null) {
			images = new ListDataModel<Image>(getBean().getImageList());
		}

		return images;
	}
	
	private String DIRECTORY_PATH = "/tmp/img-fixme4trade/";

	public void processFileUpload(FileUploadEvent event) throws IOException {
		
		try {
			Image img = new Image();
			img.setImageDirectory(DIRECTORY_PATH);
			
			String imgID = String.valueOf(img.hashCode())+".jpeg";
			
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			System.out.println("IMG ID =" +imgID);
			
			img.setImageFileName(imgID);
			
			FileUploader.saveFile(img.getFullPath(), event);
			
			this.getBean().getImageList().add(img);
			
			//imageBC.insert(img);
			
			//FacesMessage msg = new FacesMessage("O Arquivo ", file.getName() + " salvo.");
			//FacesContext.getCurrentInstance().addMessage("msgUpdate", msg);
			
			
		}

		catch (Exception ex) {

			ex.printStackTrace();

		}
	}

}
